package com.yunhai.device.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yunhai.common.dto.GlobalException;
import com.yunhai.device.mapper.SysVersionLastMapper;
import com.yunhai.device.mapper.SysVersionPartMapper;
import com.yunhai.device.service.SysVersionPartService;
import com.yunhai.model.entity.sys.SysVersionLastEntity;
import com.yunhai.model.entity.sys.SysVersionPartEntity;
import com.yunhai.model.vo.sys.SysVersionManageVo;
import com.yunhai.model.vo.sys.SysVersionTotal;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysVersionPartServiceImpl implements SysVersionPartService {

    @Resource
    private SysVersionPartMapper sysVersionPartMapper;
    @Resource
    private SysVersionLastMapper sysVersionLastMapper;


    @Transactional
    public void saveVersionContentWithFile(MultipartFile file, SysVersionManageVo sysVersionManageVo) throws  Exception {
        int bufferSize = 1024; // 1kb = 1024 bytes
        byte[] buffer = new byte[bufferSize];

        List<String>  tempList = new ArrayList<>();
        long totalSize = 0;
        try (
                InputStream fis = file.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(fis)) {
            int bytesRead;
            while ((bytesRead = bis.read(buffer)) != -1) {
                totalSize+= bytesRead;
                // 只处理实际读取到的字节数组，避免填充的0
                byte[] dataToEncode = new byte[bytesRead];
                System.arraycopy(buffer, 0, dataToEncode, 0, bytesRead);
                String base64Encoded = Base64.getEncoder().encodeToString(dataToEncode);
                System.out.println(base64Encoded); // 打印或处理Base64编码的数据
                tempList.add(base64Encoded);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        String fwVer =sysVersionManageVo.getVersion();
        String deviceType =  sysVersionManageVo.getPlatformId()+""; // "PullTeaMachine";
        SysVersionLastEntity versionLastEntity = new SysVersionLastEntity();
        versionLastEntity.setDeviceType(deviceType);
        versionLastEntity.setLastVersion(fwVer);
        sysVersionLastMapper.insert(versionLastEntity);

//        Long fwSize = (long) base64EncodedString.length();
        Integer index = 1;
        for( String item : tempList ){
            SysVersionPartEntity sysVersionPartEntity = new SysVersionPartEntity();
            sysVersionPartEntity.setIndexNum(index++);
            sysVersionPartEntity.setFwVer(fwVer);
            sysVersionPartEntity.setFwSize(totalSize);
            sysVersionPartEntity.setPktSize((long)item.length());
            sysVersionPartEntity.setCreateTime(new Date());
            sysVersionPartEntity.setContent(item);
            sysVersionPartEntity.setDeviceType("PullTeaMachine");
            sysVersionPartMapper.insert(sysVersionPartEntity);
        }
    }

    @Transactional
    public void saveVersionFileContent(  ) throws Exception {

        String filePath = "/Users/mengze/Desktop/Release_chuping_12.19_gen.bin";
        int bufferSize = 1024; // 1kb = 1024 bytes
        byte[] buffer = new byte[bufferSize];

        List<String>  tempList = new ArrayList<>();
        long totalSize = 0;
        try (
                FileInputStream fis = new FileInputStream(filePath);
             BufferedInputStream bis = new BufferedInputStream(fis)) {
                    int bytesRead;
                    while ((bytesRead = bis.read(buffer)) != -1) {
                        totalSize+= bytesRead;
                        // 只处理实际读取到的字节数组，避免填充的0
                        byte[] dataToEncode = new byte[bytesRead];
                        System.arraycopy(buffer, 0, dataToEncode, 0, bytesRead);
                        String base64Encoded = Base64.getEncoder().encodeToString(dataToEncode);
                        System.out.println(base64Encoded); // 打印或处理Base64编码的数据
                        tempList.add(base64Encoded);
                    }
        } catch (IOException e) {
            e.printStackTrace();
        }

        String fwVer = "v202505181249";
        String deviceType = "PullTeaMachine";
        SysVersionLastEntity versionLastEntity = new SysVersionLastEntity();
        versionLastEntity.setDeviceType(deviceType);
        versionLastEntity.setLastVersion(fwVer);
        sysVersionLastMapper.insert(versionLastEntity);

//        Long fwSize = (long) base64EncodedString.length();
        Integer index = 1;
        for( String item : tempList ){
            SysVersionPartEntity sysVersionPartEntity = new SysVersionPartEntity();
            sysVersionPartEntity.setIndexNum(index++);
            sysVersionPartEntity.setFwVer(fwVer);
            sysVersionPartEntity.setFwSize(totalSize);
            sysVersionPartEntity.setPktSize((long)item.length());
            sysVersionPartEntity.setCreateTime(new Date());
            sysVersionPartEntity.setContent(item);
            sysVersionPartEntity.setDeviceType("PullTeaMachine");
            sysVersionPartMapper.insert(sysVersionPartEntity);
        }
    }

    @Override
    public SysVersionTotal getVersionFileTotalData( String deviceType,String version ) throws Exception {

        LambdaQueryWrapper<SysVersionPartEntity> lqs = new LambdaQueryWrapper<>();
        lqs.eq(SysVersionPartEntity::getFwVer, version)
                .eq(SysVersionPartEntity::getDeviceType, deviceType)
                .select(
                    SysVersionPartEntity::getFwVer,
                    SysVersionPartEntity::getIndexNum,
                    SysVersionPartEntity::getFwSize,
                    SysVersionPartEntity::getPktSize,
                    SysVersionPartEntity::getFwCrc
                );

        List<SysVersionPartEntity> sysVersionPartEntities = sysVersionPartMapper.selectList(lqs);

        SysVersionTotal sysVersionTotal = new SysVersionTotal();
        sysVersionTotal.setFwPkgAmount(sysVersionPartEntities.size());
        //总的包数量
        sysVersionTotal.setFwSize(sysVersionPartEntities.get(0).getFwSize());
        sysVersionTotal.setFwVer(sysVersionPartEntities.get(0).getFwVer());
        sysVersionTotal.setFwCrc(sysVersionPartEntities.get(0).getFwCrc());
        sysVersionTotal.setList(sysVersionPartEntities.stream().map(item->item.getIndexNum()).collect(Collectors.toList()));

        return sysVersionTotal;
    }

    @Override
    public SysVersionPartEntity getVersionFilePartData(String deviceType,String fwVer, Integer index) throws Exception {

        LambdaQueryWrapper<SysVersionPartEntity> lqs = new LambdaQueryWrapper();
        lqs.eq( SysVersionPartEntity::getDeviceType, deviceType );
        lqs.eq( SysVersionPartEntity::getFwVer, fwVer );
        lqs.eq( SysVersionPartEntity::getIndexNum, index );
        SysVersionPartEntity sysVersionPartEntity = sysVersionPartMapper.selectOne(lqs);
        return sysVersionPartEntity;
    }


    public String getLastVersionOfDeviceType( String deviceType, String fwVer ) throws Exception {
        SysVersionLastEntity versionLastEntity = getLastVersionOfDeviceType(deviceType);
        if( versionLastEntity == null ){
            return null;
        }
        String lastVersion = versionLastEntity.getLastVersion();
        if( fwVer == null ){
            return  lastVersion;
        }

        //如果数据库存储的版本大于机器的版本，则需要更新。
        boolean isNeedUpdate = lastVersion.toLowerCase().compareTo(fwVer.toLowerCase()) > 0;
        return isNeedUpdate ? lastVersion : null ;
    }
    /**
     * 获取最新版本号
     * */
    private SysVersionLastEntity getLastVersionOfDeviceType( String deviceType ) throws Exception {
        LambdaQueryWrapper<SysVersionLastEntity> lqs = new LambdaQueryWrapper();
        lqs.eq(SysVersionLastEntity::getDeviceType, deviceType);
        lqs.orderByDesc( SysVersionLastEntity::getCreateTime );

        List<SysVersionLastEntity> sysVersionLastEntitys = sysVersionLastMapper.selectList(lqs);
        if( sysVersionLastEntitys != null ){
            return sysVersionLastEntitys.get(0);
        }
        return null;
    }

    /**
     * 更新最新版本好
     * */




}
